package com.shicijiaoliu.utils;


import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Component
public class MailMsg {


    public static JavaMailSenderImpl JavaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.163.com");
        mailSender.setUsername("19025982629@163.com");
        mailSender.setPassword("PGVZQIZXGBOLCUUL");
        return mailSender;
    }


    public  static String mail(String email) {

        MimeMessage mimeMessage = JavaMailSender().createMimeMessage();
        //生成随机验证码
        String code = CodeGeneratorUtil.generateCode(6);
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
        } catch (jakarta.mail.MessagingException e) {
            throw new RuntimeException(e);
        }
        //设置一个html邮件信息
        try {
            helper.setText("诗词交流平台*你的验证码为：" + code + "(有效期为一分钟)");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        //设置邮件主题名
        try {
            helper.setSubject("诗词交流平台----验证码");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        //发给谁-》邮箱地址
        try {
            helper.setTo(email);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        //谁发的-》发送人邮箱
        try {
            helper.setFrom("19025982629@163.com");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        JavaMailSender().send(mimeMessage);
        return code;
    }
}